package com.atguigu.dga.governance.assessor;

import com.atguigu.dga.governance.bean.AssessParam;
import com.atguigu.dga.governance.bean.GovernanceAssessDetail;
import org.springframework.stereotype.Component;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.math.BigDecimal;
import java.util.Date;

/**
 * @Description: 考评器
 * @Author: lay
 * @Date: 2024/6/26 19:08
 */
@Component
public abstract class Assessor {

    /**
     * 考评流程控制
     * @return
     */
    public final GovernanceAssessDetail doAssess(AssessParam assessParam){
        //1. 创建考评结果对象
        GovernanceAssessDetail governanceAssessDetail = null;
        try {
            //2. 给考评结果对象赋值
            governanceAssessDetail = GovernanceAssessDetail.builder()
                    .assessDate(assessParam.getAssessDate())
                    .tableName(assessParam.getTableMetaInfo().getTableName())
                    .schemaName(assessParam.getTableMetaInfo().getSchemaName())
                    .metricId(assessParam.getGovernanceMetric().getId().toString())
                    .metricName(assessParam.getGovernanceMetric().getMetricName())
                    .governanceType(assessParam.getGovernanceMetric().getGovernanceType())
                    .tecOwner(assessParam.getTableMetaInfo().getTableMetaInfoExtra().getTecOwnerUserName())
                    //先给满分
                    .assessScore(BigDecimal.TEN)
                    .createTime(new Date())
                    .build();

            //3. 查找问题
            checkProblem(governanceAssessDetail, assessParam);
            
            //治理处理路径
            if (assessParam.getGovernanceMetric().getGovernanceUrl() != null && governanceAssessDetail.getAssessScore().longValue() < 10L){
                String governanceUrl = assessParam.getGovernanceMetric().getGovernanceUrl();
                String realUrl = governanceUrl.replace("{tableId}", assessParam.getTableMetaInfo().getId().toString());
                governanceAssessDetail.setGovernanceUrl(realUrl);
            }

        } catch (Exception e) {
            governanceAssessDetail.setIsAssessException("1");
            StringWriter stringWriter = new StringWriter();
            e.printStackTrace(new PrintWriter(stringWriter));
            String writerString = stringWriter.toString();
            //报错信息太长的话，截断一下
            String substring = writerString.substring(0, Math.min(writerString.length(), 2000));
            governanceAssessDetail.setAssessExceptionMsg(substring);
        }
        
        //4. 返回结果
        return governanceAssessDetail;
    }

    public abstract void checkProblem(GovernanceAssessDetail governanceAssessDetail, AssessParam assessParam) throws Exception;
}
